package com.ml.carManager.utils.auth;

import android.content.Context;


import com.google.gson.JsonObject;
import com.hjq.toast.ToastUtils;

import custom.base.entity.Dict;
import custom.base.entity.auth.LoginUser;

import com.ml.carManager.utils.auth.callback.OnAuthListener;
import com.ml.carManager.net.NetProxyListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import custom.base.data.Global;
import custom.base.entity.auth.User;
import custom.base.entity.base.BaseResponse;
import custom.base.http.TokenManager;
import custom.base.http.listener.AliveCallback;
import custom.base.http.retrofit.IRequest;
import custom.base.utils.TxtUtil;
import custom.base.utils.store.PreferencesManager;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;

/**
 * Created by cubebox on 2017/7/24.
 */

public class AuthManager {
    private static AuthManager instance = null;
    private PreferencesManager preferencesManager = null;
    private Context context;
    private Call<BaseResponse<LoginUser>> call;
    /**
     * 用户登陆后的对象
     */
    private LoginUser LoginUser = null;
    private List<Dict> dictList = null;
    private HashMap<String, String> dictMap = new HashMap<>();

    public AuthManager(Context context) {
        this.context = context;
        preferencesManager = PreferencesManager.getInstance(context);
    }

    public static AuthManager getInstance(Context context) {
        synchronized (AuthManager.class) {
            if (instance == null)
                instance = new AuthManager(context);
        }
        return instance;
    }

    public static AuthManager getInstance() {
        return instance;
    }

    /**
     * 登录操作，如果已经登录了则会执行自动登录操作
     */
    public void login(final String username, final String password, String captchaVerification, final AliveCallback aliveCallback, final OnAuthListener onAuthListener) {
        if (call != null)
            call.cancel();

//        String tmp = JPushInterface.getRegistrationID(context);
        JsonObject object = new JsonObject();
        object.addProperty("username", username);
        object.addProperty("password", password);
        object.addProperty("captchaVerification", captchaVerification);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), object.toString());
        call = IRequest.getInstance(aliveCallback.currentContext()).getAppApi().login(body);
        call.enqueue(new NetProxyListener<LoginUser>(aliveCallback) {
            @Override
            public void onResponseSuccess(Call call, BaseResponse<LoginUser> response) {
                //保存用户名和密码
                preferencesManager.putString(preferencesManager.PRE_LOGIN_NAME, username);
                preferencesManager.putString(preferencesManager.PRE_LOGIN_PASSWORD, password);
                AuthManager.this.LoginUser = null;

                //保存用户到本地数据库
                LoginUser loginUser = response.getData();
                if (loginUser == null) {
                    if (onAuthListener != null)
                        onAuthListener.onAuthFail(false, response, new Throwable("请求成功但用户对象为空"));
                    return;
                }
                TokenManager.getInstance(context).saveToken(loginUser.getAccessToken());

                //查询用户信息接口
                Call<BaseResponse<LoginUser>> call2 = IRequest.getInstance(aliveCallback.currentContext()).getAppApi().getUserInfo();
                call2.enqueue(new NetProxyListener<LoginUser>(aliveCallback) {
                    @Override
                    protected boolean dealNullResponseData() {
                        return true;
                    }

                    @Override
                    public void onResponseSuccess(Call call, BaseResponse<LoginUser> response) {
                        LoginUser user = response.getData();

                        try {
                            User user1 = user.getUser();
                            loginUser.setUserId(user1.getId());
                            loginUser.setNickname(user1.getNickname());
                            loginUser.setAvatar(user1.getAvatar());
                            loginUser.setPosts(user.getPosts());
                            if (loginUser.getPosts() == null || loginUser.getPosts().size() == 0) {
                                if (onAuthListener != null)
                                    onAuthListener.onAuthFail(true, null, new Throwable("该账号未配置角色，请联系管理员"));
                                return;
                            }

                            //查询用户信息接口
                            Call<BaseResponse<List<Dict>>> call3 = IRequest.getInstance(aliveCallback.currentContext()).getAppApi().getAllDictList();
                            call3.enqueue(new NetProxyListener<List<Dict>>(aliveCallback) {
                                @Override
                                protected boolean dealNullResponseData() {
                                    return true;
                                }

                                @Override
                                public void onResponseSuccess(Call call, BaseResponse<List<Dict>> response) {
                                    List<Dict> list = response.getData();

                                    try {
                                        saveDict(list);
                                        preferencesManager.putObject(preferencesManager.PRE_USERBASE, loginUser);
                                        //授权回调
                                        if (onAuthListener != null)
                                            onAuthListener.onAuthSuccess(loginUser);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        if (onAuthListener != null)
                                            onAuthListener.onAuthFail(true, null, new Throwable("用户数据格式解析失败"));
                                        return;
                                    }
                                }

                                @Override
                                public void onResponseError(Call call, Throwable t) {
                                    super.onResponseError(call, t);
                                    if (onAuthListener != null)
                                        onAuthListener.onAuthFail(true, null, new Throwable(response.getMsg()));
                                }

                                @Override
                                public void onResponseCodeError(Call call, BaseResponse<List<Dict>> response) {
                                    super.onResponseCodeError(call, response);
                                    if (onAuthListener != null)
                                        onAuthListener.onAuthFail(true, null, new Throwable(response.getMsg()));
                                }
                            });


                        } catch (Exception e) {
                            e.printStackTrace();
                            if (onAuthListener != null)
                                onAuthListener.onAuthFail(true, null, new Throwable("用户数据格式解析失败"));
                            return;
                        }


                    }

                    @Override
                    public void onResponseError(Call call, Throwable t) {
                        super.onResponseError(call, t);
                        if (onAuthListener != null)
                            onAuthListener.onAuthFail(true, null, new Throwable(response.getMsg()));
                    }

                    @Override
                    public void onResponseCodeError(Call call, BaseResponse<LoginUser> response) {
                        super.onResponseCodeError(call, response);
                        if (onAuthListener != null)
                            onAuthListener.onAuthFail(true, null, new Throwable(response.getMsg()));
                    }
                });


            }

            @Override
            public void onResponseCodeError(Call call, BaseResponse<LoginUser> response) {
                ToastUtils.show(response.getMsg());
                if (onAuthListener != null)
                    onAuthListener.onAuthFail(true, response, new Throwable(response.getMsg()));
            }

            @Override
            public void onResponseError(Call call, Throwable t) {
                super.onResponseError(call, t);
                if (onAuthListener != null)
                    onAuthListener.onAuthFail(false, null, t);
            }
        });
    }

    /**
     * 得到用户对象,如果知道用户信息发生改变的话请调用updateUserInfo 方法更新用户信息
     */
    public LoginUser getLoginUser() {
        if (LoginUser == null)
            LoginUser = (LoginUser) preferencesManager.getObject(preferencesManager.PRE_USERBASE, LoginUser.class);
        return LoginUser;
    }

    /**
     * 更新用户信息,如果知道用户信息发生改变的话请调用updateUserInfo 方法更新用户信息
     */
    public void updateUserInfo(LoginUser loginUser) {
        this.LoginUser = loginUser;
        preferencesManager.putObject(preferencesManager.PRE_USERBASE, loginUser);
    }

    /**
     * 存储字典
     */
    public void saveDict(List<Dict> list) {
        preferencesManager.putObject(preferencesManager.PRE_ALL_DICT, list);
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                dictMap.put(list.get(i).getDictType() + list.get(i).getValue(), list.get(i).getLabel());
            }
        }

    }

    /**
     * 存储字典
     */
    public List<Dict> getDictList() {
        if (dictList == null) {
            dictList = preferencesManager.getArray(preferencesManager.PRE_ALL_DICT, Dict.class);
        }

        return dictList;
    }

    /**
     * 存储字典
     *
     * @param type 需要查询的字典
     */
    public List<Dict> getDictList(String type) {
        List<Dict> dictList = getDictList();

        List<Dict> resList = new ArrayList<>();
        for (int i = 0; i < dictList.size(); i++) {
            if (TxtUtil.equals(dictList.get(i).getDictType(), type)) {
                resList.add(dictList.get(i));
            }
        }
        return resList;
    }

    /**
     * 得到字典的标签
     */
    public String getDictLabel(String type, Integer value) {
        String label = dictMap.get(type + value);
        if (TxtUtil.isEmpty(label)) {
            label = "匹配失败";
        }
        return label;

    }

    /**
     * 是否已经授权
     */
    public boolean isAuth() {
        LoginUser LoginUser = LoginUser = (LoginUser) preferencesManager.getObject(preferencesManager.PRE_USERBASE, LoginUser.class);
        boolean flag;

        if (LoginUser == null) {
            flag = false;
        } else {
            //如果不为空则判断用户id是否为空
            if (LoginUser.getUserId() != null) {
                flag = true;
            } else {
                flag = false;
            }
        }

        return flag;
    }

    /**
     * 清楚授权
     *
     * @param clearPassword 清楚密码
     */
    public void clearAuth(boolean clearPassword) {
        preferencesManager.putString(preferencesManager.PRE_USERBASE, "");
        if (clearPassword && Global.getInstance().isReleaseMode()) {
            //清除保存的密码
            preferencesManager.putString(preferencesManager.PRE_LOGIN_PASSWORD, "");
        }
        TokenManager.getInstance(context).clearToken();
    }

    /**
     * 清除记录用户名
     */
    public void clearAuthUserName() {
        preferencesManager.putString(preferencesManager.PRE_LOGIN_NAME, "");
    }

    /**
     * 清除记录密码
     */
    public void clearAuthPassword() {
        preferencesManager.putString(preferencesManager.PRE_LOGIN_PASSWORD, "");
    }

    /**
     * 得到用户的账户
     */
    public String getAccount() {
        return preferencesManager.getString(PreferencesManager.PRE_LOGIN_NAME, "");
    }

    /**
     * 得到用户的账户
     */
    public String getAccountPassword() {
        return preferencesManager.getString(PreferencesManager.PRE_LOGIN_PASSWORD, "");
    }

    /**
     * 是否有此权限
     */
    public boolean hasPermission(String permission) {
        boolean flag = false;
        if (getLoginUser() == null)
            return flag;
        List<String> list = getLoginUser().getPermissions();
        if (list != null) {
            flag = list.contains(permission);
        }
        return flag;
    }

}
